package com.example.apidocserver.domain.user.event.impl;

import com.example.apidocserver.domain.user.entity.UsrUserAuths;
import com.example.apidocserver.domain.user.entity.UsrUsers;
import com.example.apidocserver.domain.user.event.UserAuthenticationEventService;
import com.example.apidocserver.domain.user.service.UsrUserAuthsService;
import com.example.apidocserver.domain.user.service.UsrUsersService;
import com.example.apidocserver.infrastructure.config.security.UserDetailsImpl;
import com.example.apidocserver.infrastructure.constants.SystemConstants;
import com.example.apidocserver.infrastructure.constants.UserConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Date;
import java.util.Objects;

/**
 * 用户认证授权服务
 *
 * @author xyqlg
 */
@Service
@Slf4j
public class UserAuthenticationEventServiceImpl implements UserAuthenticationEventService {
    @Resource
    private UsrUsersService usrUsersService;

    @Resource
    private UsrUserAuthsService usrUserAuthsService;

    private BCryptPasswordEncoder bc = new BCryptPasswordEncoder();

    @Override
    public UserDetails queryUserDeTailsByUsername(String username) {
        return usrUsersService.queryUserDeTailsByUsernameAndType(username, UserConstants.IDT_NAME_PW);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserDetails getUserByTourists(String userIp) {
        UserDetails userDetails = usrUsersService.queryUserDeTailsByUsernameAndType(userIp, UserConstants.IDT_TOURISTS);
        if (Objects.nonNull(userDetails)) {
            ((UserDetailsImpl) userDetails).setDataRoleValList(Collections.singletonList(1));
            return userDetails;
        }
        Date now = new Date();
        UsrUsers user = new UsrUsers().setNickName("游客").setEnabled(SystemConstants.YES).setLocked(SystemConstants.NO)
                .setExpired(SystemConstants.NO).setAvatarImgId(3L);
        user.setCreateTime(now).setUpdateTime(now);
        usrUsersService.insert(user);

        UsrUserAuths usrUserAuths = new UsrUserAuths();
        usrUserAuths.setUserId(user.getUserId()).setIdentifierType(UserConstants.IDT_TOURISTS)
                .setIdentifier(userIp).setCredential(bc.encode(userIp)).setCreateTime(now).setUpdateTime(now);
        usrUserAuthsService.insert(usrUserAuths);

        UserDetailsImpl result = usrUsersService.getUserDetails(usrUserAuths, user);
        result.setDataRoleValList(Collections.singletonList(1));
        return result;
    }
}
